var express = require('express');
var router = express.Router();
var Category = require('../models/Category');
var Content = require('../models/Content');

//通用数据
// router.use(function(req,res,next) {
//     data = {
//         userInfo:req.userInfo,
//         categories:[]
//     };

//     Category.find().then(function(categories) {
//         console.log(categories);
//         data.cates = categories;
//         return Content.where().count();
//     });
// });

var data = {
    categories:[],
    limit:5,
    count:0,
    pages:0
};
router.use(function(req,res,next){
    data.userInfo = req.userInfo;
    Category.find().then(function(cates){
        data.cates = cates;
        next();
    })
})


router.get('/',function(req , res, next){
    data.userInfo = req.userInfo;
    data.category = req.query.category || '';
    data.page = req.query.page || 1;
    var where = {};

    if(data.category) {
        where.category = data.category;
    }

    Category.find().then(function(categories) {
        // console.log(categories);
        data.cates = categories;
        return Content.where(where).count();
    }).then(function(count) {
        data.count = count;

        data.pages = Math.ceil(data.count / data.limit);

        data.page = Math.min(data.page,data.pages);

        data.page = Math.max(data.page,1);

        var skip = (data.page - 1) * data.limit;

        return Content.find(where).limit(data.limit).skip(skip).populate(['category','user']).sort({
            addTime:-1
        });
    }).then(function(contents) {
        data.contents = contents;
        // console.log(data);
        res.render('main/index',data);
    });
});


// router.get('/view',function(req,res) {
//     var contentId = req.query.content || '';

//     Content.findOne({
//         _id:contentId
//     }).then(function(content) {
//         content.views++;
//         content.save();
//         data.content = content;
//         res.render('main/content_view',data);
//     });
// });

router.get('/view',function(req,res,next){
    var id = req.query.content;
    Content.findOne({
        _id:id
    }).populate('user').then(function(contentInfo){
        data.content = contentInfo;
        contentInfo.views++;
        contentInfo.save();
        res.render('main/content_view',data);
    });
})




































module.exports = router;